# -*- coding: utf-8 -*-
from django.http import HttpResponse
from mainApp.models import NfcTag, Vot, Consulta, Dispositiu
from sorl.thumbnail.shortcuts import get_thumbnail
import traceback
try:
    import simplejson as json
except ImportError:
    import json


def votar(request):
    try:
        mvot = request.GET['vot']
        mconsultaid = request.GET['consulta']
        mdispositiuid = int(request.GET['dispositiu'])
        mnfctagid = request.GET['nfctagid']
        mnfctag = NfcTag.objects.get(tagid=mnfctagid)
        mconsulta = Consulta.objects.get(pk=mconsultaid)
        try:
            mdispositiu = Dispositiu.objects.get(dispositiuid=mdispositiuid)
        except:
            mdispositiu = Dispositiu(dispositiuid=mdispositiuid)
            mdispositiu.save()
        try:
            mVot = Vot.objects.get(dispositiu=mdispositiu,
                                   consulta=mconsulta)
            mVot.vot = mvot
        except:
            mVot = Vot(vot=mvot,
                       dispositiu=mdispositiu,
                       consulta=mconsulta,
                       nfctag=mnfctag)
        mVot.save()
        testdict = {'response_status': '0'}
        return HttpResponse(json.dumps(testdict), mimetype="application/json")
    except:
        traceback.print_exc()
        testdict = {'response_status': '-1'}
        return HttpResponse(json.dumps(testdict), mimetype="application/json")


def ConsultaIdByTagId(request):
    try:
        mnfctagid = request.GET['nfctagid']
        mnfctag = NfcTag.objects.get(tagid=mnfctagid)
        testdict = {'response_status': '0',
                    'consultaid': mnfctag.consulta.pk}
        return HttpResponse(json.dumps(testdict), mimetype="application/json")
    except:
        testdict = {'response_status': '-1'}
        return HttpResponse(json.dumps(testdict), mimetype="application/json")


def InfoConsulta(request):
    mconsultapk = request.GET['consulta']
    mconsulta = Consulta.objects.get(pk=mconsultapk)
    im380x380 = get_thumbnail(mconsulta.logo_consulta,
                              '380x380',
                              crop='center',
                              quality=85)
    im720x400 = get_thumbnail(mconsulta.logo_consulta,
                              '720x400',
                              crop='center',
                              quality=85)
    testdict = {'response_status': '0',
                'nom': mconsulta.nom,
                'descripcio_extesa': mconsulta.descripcio_extesa,
                'logo_consulta': im380x380.url,
                'logo_consulta_pano': im720x400.url}
    return HttpResponse(json.dumps(testdict), mimetype="application/json")
